using IDSReferenceToken.EntityFrameworkCore;
using IDSReferenceToken.MultiTenancy;
using Microsoft.AspNetCore.Cors;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;
using Volo.Abp;
using Volo.Abp.Account.Web;
using Volo.Abp.AspNetCore.Authentication.JwtBearer;
using Volo.Abp.AspNetCore.MultiTenancy;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc.UI.Bundling;
using Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic;
using Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic.Bundling;
using Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared;
using Volo.Abp.AspNetCore.Serilog;
using Volo.Abp.Autofac;
using Volo.Abp.IdentityServer;
using Volo.Abp.Localization;
using Volo.Abp.Modularity;
using Volo.Abp.Swashbuckle;
using Volo.Abp.UI.Navigation.Urls;
using Volo.Abp.VirtualFileSystem;

namespace IDSReferenceToken
{
    [DependsOn(
        typeof(IDSReferenceTokenHttpApiModule),
        typeof(AbpAutofacModule),
        typeof(AbpAspNetCoreMultiTenancyModule),
        typeof(IDSReferenceTokenApplicationModule),
        typeof(IDSReferenceTokenEntityFrameworkCoreDbMigrationsModule),
        typeof(AbpAspNetCoreMvcUiBasicThemeModule),
        typeof(AbpAspNetCoreAuthenticationJwtBearerModule),
        typeof(AbpAccountWebIdentityServerModule),
        typeof(AbpAspNetCoreSerilogModule),
        typeof(AbpSwashbuckleModule)
    )]
    public class IDSReferenceTokenHttpApiHostModule : AbpModule
    {
        private const string DefaultCorsPolicyName = "Default";

        public override void PreConfigureServices(ServiceConfigurationContext context)
        {
            // 禁用自动生成 tempkey.jwk
            PreConfigure<AbpIdentityServerBuilderOptions>(builder =>
            {
                builder.AddDeveloperSigningCredential = false;
            });

            // 配置使用用户自定义的 jwk
            // 该 jwk 有 jwkdemo 工具生成
            PreConfigure<IIdentityServerBuilder>(builder =>
            {
                var baseDir = Path.GetDirectoryName(typeof(IDSReferenceTokenHttpApiHostModule).Assembly.Location)
                ?? throw new InvalidOperationException("程序集 IDSReferenceTokenHttpApiHostModule 目录为空！");

                var fileName = Path.Combine(baseDir, "Assets/ids.jwk");

                if (!File.Exists(fileName)) throw new InvalidOperationException($"{fileName} 文件不存在！");

                var json = File.ReadAllText(fileName);
                var jwk = new JsonWebKey(json);
                builder.AddSigningCredential(jwk, jwk.Alg);
            });
        }

        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var configuration = context.Services.GetConfiguration();
            var hostingEnvironment = context.Services.GetHostingEnvironment();

            ConfigureBundles();
            ConfigureUrls(configuration);
            ConfigureConventionalControllers();
            ConfigureAuthentication(context, configuration);
            ConfigureLocalization();
            ConfigureVirtualFileSystem(context);
            ConfigureCors(context, configuration);
            ConfigureSwaggerServices(context, configuration);
        }

        private void ConfigureBundles()
        {
            Configure<AbpBundlingOptions>(options =>
            {
                options.StyleBundles.Configure(
                    BasicThemeBundles.Styles.Global,
                    bundle => { bundle.AddFiles("/global-styles.css"); }
                );
            });
        }

        private void ConfigureUrls(IConfiguration configuration)
        {
            Configure<AppUrlOptions>(options =>
            {
                options.Applications["MVC"].RootUrl = configuration["App:SelfUrl"];
                options.RedirectAllowedUrls.AddRange(configuration["App:RedirectAllowedUrls"]?.Split(',') ?? throw new InvalidOperationException("App:RedirectAllowedUrls is null."));
            });
        }

        private void ConfigureVirtualFileSystem(ServiceConfigurationContext context)
        {
            var hostingEnvironment = context.Services.GetHostingEnvironment();

            if (hostingEnvironment.IsDevelopment())
            {
                Configure<AbpVirtualFileSystemOptions>(options =>
                {
                    options.FileSets.ReplaceEmbeddedByPhysical<IDSReferenceTokenDomainSharedModule>(
                        Path.Combine(hostingEnvironment.ContentRootPath,
                            $"..{Path.DirectorySeparatorChar}IDSReferenceToken.Domain.Shared"));
                    options.FileSets.ReplaceEmbeddedByPhysical<IDSReferenceTokenDomainModule>(
                        Path.Combine(hostingEnvironment.ContentRootPath,
                            $"..{Path.DirectorySeparatorChar}IDSReferenceToken.Domain"));
                    options.FileSets.ReplaceEmbeddedByPhysical<IDSReferenceTokenApplicationContractsModule>(
                        Path.Combine(hostingEnvironment.ContentRootPath,
                            $"..{Path.DirectorySeparatorChar}IDSReferenceToken.Application.Contracts"));
                    options.FileSets.ReplaceEmbeddedByPhysical<IDSReferenceTokenApplicationModule>(
                        Path.Combine(hostingEnvironment.ContentRootPath,
                            $"..{Path.DirectorySeparatorChar}IDSReferenceToken.Application"));
                });
            }
        }

        private void ConfigureConventionalControllers()
        {
            Configure<AbpAspNetCoreMvcOptions>(options =>
            {
                options.ConventionalControllers.Create(typeof(IDSReferenceTokenApplicationModule).Assembly);
            });
        }

        private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
        {
            context.Services.AddAuthentication()
                .AddJwtBearer(options =>
                {
                    // 获取或设置在执行 OpenIdConnect 调用时使用的 Authority。
                    options.Authority = configuration["AuthServer:Authority"];
                    // 设置任何收到的 OpenIdConnect 令牌的单个有效受众值。 如果此属性为空，此值将传递到 TokenValidationParameters.ValidAudience 中。
                    options.Audience = configuration["AuthServer:Audience"];
                    // 获取或设置元数据地址或颁发机构是否需要 HTTPS, 默认值为 true。 这只能在开发环境中禁用。
                    options.RequireHttpsMetadata = Convert.ToBoolean(configuration["AuthServer:RequireHttpsMetadata"]);
                    // 用于检索元数据的 HttpMessageHandler。 除非值为 WebRequestHandler，否则不能在设置 BackchannelCertificateValidator 的同时设置此项。
                    options.BackchannelHttpHandler = new HttpClientHandler
                    {
                        ServerCertificateCustomValidationCallback =
                            HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                    };

                    var symmetricSecurityKey = configuration["AuthServer:IssuerSigningKey"] ?? throw new InvalidOperationException("AuthServer:SymmetricSecurityKey is null.");
                    var issuer = configuration["AuthServer:Issuer"] ?? throw new InvalidOperationException("AuthServer:Issuer is null.");

                    // 置用于验证标识令牌的参数。
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        // 验证签名
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(symmetricSecurityKey)),
                        // 验证发布者
                        ValidIssuer = issuer,
                        // 需要 Audience
                        RequireAudience = true,
                        // 验证 Audience
                        ValidateAudience = true,
                        // 设置 ValidAudience
                        ValidAudience = configuration["AuthServer:Audience"],
                        // 启用令牌过期时间
                        ValidateLifetime = true,
                        // 设置为获取到 Token 后就开始计时
                        ClockSkew = TimeSpan.Zero,
                        // 需要设置过期时间
                        RequireExpirationTime = true,
                    };

                    // 用于为身份验证处理程序默认将所有身份验证操作转发到的当前请求选择默认方案。
                    // 默认转发逻辑将首先检查最具体的 ForwardAuthenticate/ Challenge / Forbid / SignIn / SignOut 设置，
                    // 然后检查 ForwardDefaultSelector，然后检查 ForwardDefault。
                    // 第一个非 null 结果将用作要转发的目标方案。
                    // if token does not contain a dot, it is a reference token
                    options.ForwardDefaultSelector = SchemeSelector.ForwardReferenceToken("introspection");
                }).AddOAuth2Introspection("introspection", options =>
                {
                    options.Authority = configuration["AuthServer:Authority"];

                    options.ClientId = configuration["AuthServer:ClientId"]; //this is name of ApiResources not client id.
                    options.ClientSecret = configuration["AuthServer:ClientSecret"];       //this is secret of ApiResources not client.
                });
        }

        private static void ConfigureSwaggerServices(ServiceConfigurationContext context, IConfiguration configuration)
        {
            context.Services.AddAbpSwaggerGenWithOAuth(
                configuration["AuthServer:Authority"] ?? throw new InvalidOperationException("AuthServer:Authority is null."),
                new Dictionary<string, string>
                {
                    {"IDSReferenceToken", "IDSReferenceToken API"}
                },
                options =>
                {
                    options.SwaggerDoc("v1", new OpenApiInfo { Title = "IDSReferenceToken API", Version = "v1" });
                    options.DocInclusionPredicate((docName, description) => true);
                });
        }

        private void ConfigureLocalization()
        {
            Configure<AbpLocalizationOptions>(options =>
            {
                options.Languages.Add(new LanguageInfo("ar", "ar", "العربية"));
                options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština"));
                options.Languages.Add(new LanguageInfo("en", "en", "English"));
                options.Languages.Add(new LanguageInfo("en-GB", "en-GB", "English (UK)"));
                options.Languages.Add(new LanguageInfo("fr", "fr", "Français"));
                options.Languages.Add(new LanguageInfo("hu", "hu", "Magyar"));
                options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português"));
                options.Languages.Add(new LanguageInfo("ru", "ru", "Русский"));
                options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe"));
                options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
                options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文"));
                options.Languages.Add(new LanguageInfo("de-DE", "de-DE", "Deutsch", "de"));
                options.Languages.Add(new LanguageInfo("es", "es", "Español", "es"));
            });
        }

        private void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
        {
            context.Services.AddCors(options =>
            {
                options.AddPolicy(DefaultCorsPolicyName, builder =>
                {
                    builder
                        .WithOrigins(
                            configuration["App:CorsOrigins"]
                                ?.Split(",", StringSplitOptions.RemoveEmptyEntries)
                                .Select(o => o.RemovePostFix("/"))
                                .ToArray() ?? throw new InvalidOperationException("App:CorsOrigins is null.")
                        )
                        .WithAbpExposedHeaders()
                        .SetIsOriginAllowedToAllowWildcardSubdomains()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                });
            });
        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();
            var env = context.GetEnvironment();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAbpRequestLocalization();

            if (!env.IsDevelopment())
            {
                app.UseErrorPage();
            }

            app.UseCorrelationId();
            app.UseStaticFiles();
            app.UseHttpsRedirection(); // 强制使用 https
            app.UseRouting();
            app.UseCors(DefaultCorsPolicyName);
            app.UseAuthentication();
            app.UseJwtTokenMiddleware();

#pragma warning disable CS0162 // Disable the unreachable code warning  
            if (MultiTenancyConsts.IsEnabled)
            {
                app.UseMultiTenancy();
            }
#pragma warning restore CS0162 // Restore the unreachable code warning

            app.UseUnitOfWork();
            app.UseIdentityServer();
            app.UseAuthorization();

            app.UseSwagger();
            app.UseAbpSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "IDSReferenceToken API");

                var configuration = context.ServiceProvider.GetRequiredService<IConfiguration>();
                c.OAuthClientId(configuration["AuthServer:SwaggerClientId"]);
                c.OAuthClientSecret(configuration["AuthServer:SwaggerClientSecret"]);
            });

            app.UseAuditing();
            app.UseAbpSerilogEnrichers();
            app.UseConfiguredEndpoints();
        }
    }
}
